
<template>
  <div class="title">{{title}}</div>
  <!-- <el-dialog v-model="dialogVisible" title="新增课程" width="800px"> -->
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <!-- <el-row :gutter="20"> -->
        <!-- <el-col :span="12"> -->

        <!-- </el-col> -->
        <!-- <el-col :span="12"> -->
          <el-form-item label="课程标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入课程标题" />
          </el-form-item>
        <!-- </el-col> -->
      <!-- </el-row> -->

  <!-- 将"是否启用"改为"课程分类" -->
  <el-form-item label="课程分类" prop="categoryId">
    <el-select v-model="form.categoryId" clearable placeholder="请选择课程分类">
      <el-option
        v-for="item in categoryOptions"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      />
    </el-select>
  </el-form-item>

  <!-- 添加"是否上架"字段 -->
  <el-form-item label="是否上架" prop="status">
    <el-select v-model="form.status" clearable placeholder="请选择上架状态">
      <el-option label="上架" value="0" />
      <el-option label="下架" value="1" />
    </el-select>
  </el-form-item>

      <!-- <el-row :gutter="20"> -->
        <!-- <el-col :span="12"> -->
          <el-form-item label="课程价格" prop="price">
            <el-input-number v-model="form.price" :min="0" :precision="2" />
          </el-form-item>
        <!-- </el-col> -->
        <!-- <el-col :span="12"> -->
          <el-form-item label="学习人数">
            <el-input-number v-model="form.studyCount" :min="0" />
          </el-form-item>
        <!-- </el-col> -->
      <!-- </el-row> -->
<!--  -->
      <!-- <el-row :gutter="20"> -->
        <!-- <el-col :span="12"> -->
          <el-form-item label="难度级别">
            <el-select v-model="form.level"  clearable placeholder="请选择">
              <el-option label="初级" :value="1" />
              <el-option label="中级" :value="2" />
              <el-option label="高级" :value="3" />
            </el-select>
          </el-form-item>
        <!-- </el-col> -->
        <!-- <el-col :span="12"> -->
          <el-form-item label="排序">
            <el-input-number v-model="form.sort" :min="0" />
          </el-form-item>
        <!-- </el-col> -->
      <!-- </el-row> -->

      <!-- <el-row :gutter="20"> -->
        <el-col :span="12">
          <el-form-item label="讲师姓名">
            <el-input v-model="form.teacherName" placeholder="请输入讲师姓名" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12"> -->
          <el-form-item label="原价">
            <el-input-number v-model="form.originalPrice" :min="0" :precision="2" />
          </el-form-item>
        <!-- </el-col> -->
      <!-- </el-row> -->

      <el-form-item label="课程简介">
        <el-input
          v-model="form.intro"
          type="textarea"
          :rows="3"
          placeholder="请输入课程简介" />
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息" />
      </el-form-item>

      <el-form-item label="封面图片">
        <el-upload
          class="upload-demo"
          action="/dev-api/ossUpload/uploadImage"
          :headers="uploadHeaders"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
          :show-file-list="false">
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">建议尺寸800x450像素，支持JPG/PNG格式</div>
          </template>
        </el-upload>
        <div class="image-preview" v-if="form.coverImg">
          <img :src="form.coverImg" class="cover-preview" />
          <div class="image-actions">
            <el-button class="del-image" type="danger" size="small" @click="removeCoverImg">删除图片</el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div class="button-group">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="danger" v-if="isEdit" @click="handleDelete">删除</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </div>
    <!-- <template #footer> -->

    <!-- </template> -->
  <!-- </el-dialog> -->
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { getToken } from '@/utils/auth'
import { getCategoryTypeList } from '@/api/bykt/course'

// 添加课程分类选项
const categoryOptions = ref([])

// 获取课程分类列表
const fetchCategoryList = async () => {
  try {
    const res = await getCategoryTypeList()
    categoryOptions.value = res.rows || []
  } catch (error) {
    console.error('获取课程分类失败:', error)
  }
}

// 在组件挂载时获取课程分类
onMounted(() => {
  fetchCategoryList()
})

// 修改表单数据结构
const form = reactive({
  categoryId: '',
  title: '',
  price: 0,
  studyCount: 0,
  level: 1,
  coverImg: '',
  intro: '',
  originalPrice: 0,
  teacherName: '',
  sort: 0,
  remark: '',
  status: "0" // 添加状态字段：0上架 1下架
})


const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  courseData: {
    type: Object,
    default: () => ({})
  }
})

const dialogVisible = ref(false)
const formRef = ref()
// const form = reactive({
//   categoryId: '',
//   title: '',
//   price: 0,
//   studyCount: 0,
//   level: 1,
//   coverImg: '',
//   intro: '',
//   originalPrice: 0,
//   teacherName: '',
//   sort: 0,
//   remark: ''
// })

// 监听courseData变化
watch(() => props.courseData, (newVal) => {
  if (props.isEdit && newVal) {
    Object.assign(form, {
      categoryId: newVal.categoryId,
      title: newVal.title,
      price: newVal.price,
      studyCount: newVal.studyCount,
      level: newVal.level,
      coverImg: newVal.coverImg,
      intro: newVal.intro,
      originalPrice: newVal.originalPrice,
      teacherName: newVal.teacherName,
      sort: newVal.sort,
      status: newVal.status,
      remark: newVal.remark
    })
  }
}, { deep: true, immediate: true })

const rules = {
  categoryId: [{ required: true, message: '请选择课程分类', trigger: 'change' }],
  title: [{ required: true, message: '请输入课程标题', trigger: 'blur' }],
  price: [{ required: true, message: '请输入课程价格', trigger: 'blur' }],
  status: [{ required: true, message: '请选择上架状态', trigger: 'change' }]
}

// 上传请求头
const uploadHeaders = {
  Authorization: 'Bearer ' + getToken()
}

// 处理上传成功
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    form.coverImg = response.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

// 删除封面图片
const removeCoverImg = () => {
  form.coverImg = ''
}

// 监听courseData变化
watch(() => props.courseData, (newVal) => {
  if (props.isEdit && newVal) {
    Object.assign(form, {
      categoryId: newVal.categoryId,
      title: newVal.title,
      price: newVal.price,
      studyCount: newVal.studyCount,
      level: newVal.level,
      coverImg: newVal.coverImg,
      intro: newVal.intro,
      originalPrice: newVal.originalPrice,
      teacherName: newVal.teacherName,
      sort: newVal.sort,
      remark: newVal.remark
    })
  }
}, { deep: true, immediate: true })

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      emit('submit', {
        ...form,
        id: props.isEdit ? props.courseData.id : undefined
      })
    }
  })
}

const beforeUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式的图片!')
    return false
  }
  return true
}

const emit = defineEmits(['submit', 'delete'])

// 处理删除
const handleDelete = () => {
  ElMessageBox.confirm(
    '确定要删除该课程吗？删除后将删除所有章节和视频！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    emit('delete', props.courseData.id)
  })
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    categoryId: '',
    title: '',
    price: 0,
    studyCount: 0,
    level: 1,
    coverImg: '',
    intro: '',
    originalPrice: 0,
    teacherName: '',
    sort: 0,
    remark: ''
  })
}

// 监听courseData变化
watch(() => props.courseData, (newVal) => {
  if (props.isEdit && newVal) {
    Object.assign(form, newVal)
  }
}, { deep: true })

// const submitForm = () => {
//   formRef.value.validate((valid) => {
//     if (valid) {
//       emit('submit', { ...form })
//     }
//   })
// }

defineExpose({
  dialogVisible,
  resetForm
})
</script>

<style scoped>
.cover-preview {
  width: 200px;
  height: 120px;
  margin-top: 10px;
  border-radius: 4px;
}

.image-preview {
  margin-top: 10px;
  margin-left: 10%;
}

.image-actions {
  margin-top: 8px;
}
.del-image{
  margin-left: 30%;
}
.title{
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}
.button-group {
  margin-top: 20px;
  text-align: center;
}
</style>
